import json

from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.core.cache import cache

from utils.response_code import RETCODE
from .models import Area, Address
# Create your views here.
from django.views import View


#显示全部地址
class AddressView(LoginRequiredMixin,View):
    #显示地址

    def get(self, request):
        user = request.user
        address_list = user.addresses.filter(is_deleted=False)
        address_dict_list = []
        for address in address_list:
            address_dict_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })

        print(user.default_address_id)
        print(address_dict_list)
        context = {
            'default_address_id': user.default_address_id,
            'addresses': address_dict_list,
        }

        return render(request, 'user_center_site.html', context)

#显示三级联动
class AreasView(LoginRequiredMixin,View):
    def get(self,request):
        area_id=request.GET.get('area_id')

        if not area_id:
            province_list=[]
            area_list=Area.objects.filter(parent__isnull=True)
            for area in area_list:
                province_list.append(
                    {'id':area.id,
                     'name':area.name
                     }
                )
            cache.set('province_list', province_list,3600)
            return_list=   {
                "code": "0",
                "errmsg": "OK",
                "province_list": province_list
            }

            return http.JsonResponse(return_list)


        area_list = Area.objects.filter(parent=area_id)
        sub_list = []
        for area in area_list:
            sub_list.append(
                {'id': area.id,
                 'name': area.name
                 }
            )
        # print(Area.objects.get(id=area_id).name)
        cache.set('sub_list'+area_id,sub_list,3600)
        return_dict= {
            "code": "0",
            "errmsg": "OK",
            "sub_data": {
                "id": area_id,
                "name": Area.objects.get(id=area_id).name,
                "subs": sub_list
            }
        }


        return http.JsonResponse(return_dict)
        # return http.HttpResponse('1')

# class CreateAddressView(LoginRequiredMixin,View):
#     #新增地址
#     def post(self,request):
#         '''
#         receiver	string	是	收货人
#         province_id	string	是	省份ID
#         city_id	string	是	城市ID
#         district_id	string	是	区县ID
#         place	string	是	收货地址
#         mobile	string	是	手机号
#         tel	string	否	固定电话
#         email	string	否	邮箱
#         :param request:
#         :return: json
#         '''
#         data=json.loads((request.body).decode())
#
#
#         count=request.user.addresses.all().count()
#
#         if count>20:
#             return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '超过地址数量上限'})
#
#         user=request.user
#
#
#         address=Address.objects.create(
#                 user=request.user,
#                 #收货人
#                 receiver=data['receiver'],
#                 #省份ID
#                 province_id=data['province_id'],
#                 #城市ID
#                 city_id=data['city_id'],
#                 # 区县ID
#                 district_id=data['district_id'],
#                 # 收货地址
#                 place=data['place'],
#                 # 手机号
#                 mobile=data['mobile'],
#                 # 固定电话
#                 tel=data['tel'],
#                 # 邮箱
#                 email=data['email']
#         )
#         # except:
#         #     print('失败')
#         #     return http.HttpResponse('失败')
#
#         address_dict = {
#             "id": address.id,
#             "title": address.title,
#             "receiver": address.receiver,
#             "province": address.province.name,
#             "city": address.city.name,
#             "district": address.district.name,
#             "place": address.place,
#             "mobile": address.mobile,
#             "tel": address.tel,
#             "email": address.email
#         }
#         if not user.default_address_id:
#             user.default_address_id=address
#             request.user.save()
#
#         return_dict={'code': RETCODE.OK,'errmsg': '新增地址成功','address':address_dict}
#         return http.JsonResponse(return_dict)
#新增地址
#新增地址
class CreateAddressView(LoginRequiredMixin,View):
    #保存地址
    def post(self,request):
        """
        receiver	string	是	收货人
        province_id	string	是	省份ID
        city_id	string	是	城市ID
        district_id	string	是	区县ID
        place	string	是	收货地址
        mobile	string	是	手机号
        tel	string	否	固定电话
        email	string	否	邮箱
        :param request:
        :return:
        """
        count = request.user.addresses.count()
        if count >= 20:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '超过地址数量上限'})
        data=json.loads(request.body.decode())
        try:
            address=Address.objects.create(
                user=request.user,
                title=data.get('receiver'),
                receiver=data.get('receiver'),
                province_id=data.get('province_id'),
                city_id=data.get('city_id'),
                district_id=data.get('district_id'),
                place=data.get('place'),
                mobile=data.get('mobile'),
                tel=data.get('tel'),
                email=data.get('email')


            )
            if not request.user.default_address:
                request.user.default_address=address
                request.user.default_address.save()
        except:
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '新增地址失败'})

        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应保存结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '新增地址成功', 'address':address_dict})


#对地址进行修改
class PutAddressView(LoginRequiredMixin,View):
    def put(self,request,address_id):
        """
        address_id	string	是	要修改的地址ID（路径参数）
        receiver	string	是	收货人
        province_id	string	是	省份ID
        city_id	string	是	城市ID
        district_id	string	是	区县ID
        place	string	是	收货地址
        mobile	string	是	手机号
        tel	string	否	固定电话
        email	string	否	邮箱
        :param request:
        :return:
        """
        print(address_id)

        data=json.loads(request.body.decode())
        try:
            Address.objects.filter(id=address_id).update(
                receiver=data['receiver'],
                province_id=data['province_id'],
                city_id=data['city_id'],
                district_id=data['district_id'],
                place=data['place'],
                mobile=data['mobile'],
                tel=data['tel'],
                email=data['email'],
            )

        except:
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '更新地址失败'})
        address=Address.objects.get(id=address_id)
        address_dict={
            'id':address.id,
            'receiver':address.receiver,
            'province':address.province.name,
            'city':address.city.name,
            'district':address.province.name,
            'place':address.place,
            'mobile':address.mobile,
            'tel':address.tel,
            'email':address.email

        }

        return http.JsonResponse({
            'code': RETCODE.OK, 'errmsg': '更新地址成功', 'address': address_dict
        })

    def delete(self,request,address_id):
        try:
            address=Address.objects.get(id=address_id)
            address.is_deleted=1
            address.save()
            #如果删除的是默认地址
            if address.user.default_address_id==int(address_id):
                print('默认')
                address.user.defult_address_id=None
                address.user.save()
        except:
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '删除地址失败'})
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除地址成功'})

#设置默认地址
class DefaultAddressView(View,LoginRequiredMixin):
    def put(self,request,address_id):

        address=Address.objects.get(id=address_id)
        address.user.default_address_id=address_id
        address.user.save()


            # return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '设置地址失败'})
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置默认地址成功'})

#修改标题
class TitleView(LoginRequiredMixin,View):
    def put(self,request,address_id):
        try:
            data=json.loads(request.body.decode())
            address=Address.objects.get(id=address_id)
            address.title=data['title']
            address.save()
            return http.JsonResponse({
                'code':RETCODE.OK,
                'errmsg':'成功'
            })
        except:
            return http.JsonResponse({
                'code':RETCODE.DBERR,
                'errmsg':'设置标题失败'
            })
























